package cn.learn.athena.controller.user;

import cn.learn.athena.api.service.UserServiceClient;
import cn.learn.athena.model.User;
import cn.learn.athena.util.Result;
import cn.learn.athena.util.Validation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zlj
 * @Date 2018/11/1
 * @des
 */

@RequestMapping("/user")
@RestController
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserServiceClient userServiceClient;

    /**
    * 功能:
    *  注册用户
    * @param user
    * @return Result
    * @date 2018/11/1
    */
    @RequestMapping(value="/addUser",method = RequestMethod.POST)
    public Result addUser(User user) {
        Validation.isTrue(StringUtils.isNotEmpty(user.getLoginName()) , "用户名不能为空");
        Result result = userServiceClient.addUser(user);
        return result ;
    }

    /**
     * 功能:
     * 登入
     * @param user
     * @return
     * @date 2019/1/4
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(User user) {
        Result<Object> result = new Result<>();
        Validation.isTrue(StringUtils.isNotEmpty(user.getLoginName()) , "用户名不能为空");
        Validation.isTrue(StringUtils.isNotEmpty(user.getPassword()) , "密码不能为空");
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        // 执行认证登陆
        subject.login(token);
        return result;
    }
}
